<?php
/**
 * 融客巴士模块处理程序
 *
 * @author junsion&kaiwen&yunjie
 * @url http://s.we7.cc/index.php?c=store&a=author&uid=74516
 */
defined('IN_IA') or exit('Access Denied');
require_once IA_ROOT.'/addons/junsion_listenbook/func.php';
class Junsion_listenbookModuleProcessor extends WeModuleProcessor {
	public function respond() {
		global $_W;
		$content = $this->message['content'];
		$openid = $this->message['from'];
		$ticket = $this->message['ticket'];
		$cfg = $this->module['config'];
		$fans = $this->getFans($openid);
		if (empty($fans['unionid']) && $cfg['multiaccount']) return $this->respText('请先绑定开放平台');
		$qr = pdo_fetch('select id,name,scene_str from '.tablename('qrcode')." where ticket='{$ticket}'");
		if(strpos($qr['scene_str'],'_agentid_') !== false){ //推广绑定
			$mem = get('select id from '.tb('mem')." where uniacid='{$_W['uniacid']}' and openid='{$openid}'");
			if (!empty($mem)) return 'success';
			$pid = str_replace($this->modulename."_agentid_", '', $qr['scene_str']);
			
			$pmem = get('select id,uniacid from '.tb('mem')." where id='{$pid}'");
			$mem = array(
					'uniacid' => $pmem['uniacid'],
					'openid' => $openid,
					'nickname' => $fans['nickname'],
					'avatar' => $fans['avatar'],
					'unionid' => $fans['unionid'],
					'agentid' => $pid,
					'createtime' => time(),
			);
			insert('mem', $mem);
			return 'success';
		}else{
			if ($cfg['multiaccount']){
				$muniacid = str_replace($this->modulename, '', $qr['name']);
				$mem = get("select id,uniacid,openid from ".tb("mem")." where uniacid='{$muniacid}' and unionid='{$fans['unionid']}'");
			}else $mem = get("select id,uniacid,openid from ".tb("mem")." where uniacid='{$_W['uniacid']}' and openid='{$openid}'");
			if (empty($mem)) return 'success';
			$mbook = get('select * from '.tb('mem_book')." where mid='{$mem['id']}' and status = 0 order by createtime desc ");
			$book = get('select id,title,paydes from '.tb('book')." where id='{$mbook['bid']}'");
			if (empty($book)) return 'success';
			$time = date('m月d日',$mbook['starttime']);
			$link = $_W['siteroot'].'app/'.$this->createMobileUrl('bindex',array('id'=>$mbook['id']));
			$link = str_replace('i='.$_W['uniacid'], 'i='.$mem['uniacid'], $link);
			$str = "亲爱的同学，恭喜你成功加入《{$book['title']}》！\n\n{$book['paydes']}\n\n个人学号：{$mbook['studentid']}\n开课时间：{$time}\n\n<a href='{$link}'>点这里听课！</a>";
			return $this->respText($str);
		}
		
	}
	
	private function getFans($openid){
		global $_W;
		load()->model('mc');
		$fans = mc_fansinfo($openid);
		if (empty($fans['nickname']) || empty($fans['avatar'])){
			$ACCESS_TOKEN = $this->getAccessToken();
			$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$ACCESS_TOKEN}&openid={$openid}&lang=zh_CN";
			load()->func('communication');
			$json = ihttp_get($url);
			$userInfo = @json_decode($json['content'], true);
			if ($userInfo['nickname']) $fans['nickname'] = $userInfo['nickname'];
			if ($userInfo['headimgurl']) $fans['avatar'] = $userInfo['headimgurl'];
			$fans['openid'] = $openid;
		}
		$fans['uniacid'] = $_W['uniacid'];
		return $fans;
	}
	
	private function getAccessToken() {
		global $_W;
		load()->model('account');
		$acid = $_W['acid'];
		if (empty($acid)) {
			$acid = $_W['uniacid'];
		}
		$account = WeAccount::create($acid);
		$token = $account->fetch_available_token();
		return $token;
	}
}